package com.zrrd.yt.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yt.model.enums.PaymentType;
import com.zrrd.yt.model.order.OrderInfo;
import com.zrrd.yt.order.client.OrderFeignClient;
import com.zrrd.yt.payment.config.AlipayConfig;
import com.zrrd.yt.payment.service.AlipayService;
import com.zrrd.yt.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HongyueYang
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String createPayCode(Long orderId) throws AlipayApiException {
        //获取订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //保存交易记录
        paymentInfoService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        //创建请求对象
        AlipayTradePayRequest alipayRequest = new AlipayTradePayRequest();
        //设置同步回调
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
        //创建一个参数集合
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",0.01);
        map.put("subject",orderInfo.getTradeBody());
        //生成一个二维码
        alipayRequest.setBizContent(JSON.toJSONString(map));
        //调用支付宝SDK生成表单（发请求）
        String body = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("请求支付结果===>"+body);
        return body;
    }
}
